from zope.interface import implements

from pyhnode import interfaces, config

import pickle

class buffer:
    def __init__(self, plugin):
        self.data = []
        self.file = config.conf.get(plugin, 'filename')
        self.size = config.conf.getint(plugin, 'bufsize')
        if (len(self.file) != 0):
            try:
                file = open(self.file, "r")
                self.data = pickle.load(file)
                file.close()
            except:
                pass
    
    def clear(self):
        pass
    
    def get(self):
        return self.data
    
    def getlast(self):
        return self.data[-1:]

class linearBuffer(buffer):

    implements(interfaces.IBuffer)

    def append(self, obj):
        if (len(self.data) < self.size):
            self.data.append(obj)
        if (len(self.file) != 0):
            file = open(self.file, "w")
            pickle.dump(self.data, file)
            file.close()
    
    def clear(self):
        self.data = []
        if (len(self.file) != 0):
            file = open(self.file, "w")
            pickle.dump(self.data, file)
            file.close()

class ringBuffer(buffer):

    implements(interfaces.IBuffer)

    def append(self, obj):
        self.data.append(obj)
        if (len(self.data) > self.size):
            self.data = self.data[1:]
        if (len(self.file) != 0):
            file = open(self.file, "w")
            pickle.dump(self.data, file)
            file.close()

__all__ = {'linear' : linearBuffer,
           'ring'   : ringBuffer}
